package main

import (
	"encoding/json"
	"fmt"
	"math/rand"
)

type Person struct {
	Name string
	Age  float32
}

func (p Person) toJson() ([]byte, error) {
	return json.Marshal(p)
}
func main() {
	fmt.Println("测试IF语句")
	p := Person{"mary", 20.0}
	if age := p.Age; age > 18 {
		toJson, _ := p.toJson()
		fmt.Printf("已是成人%s\n", toJson)
	}

	fmt.Println("测试switch语句")
	switch num := rand.Intn(10); num {
	case 8:
		fmt.Println("is 10")
	default:
		fmt.Printf("%d is not 10\n", num)
	}
	fmt.Println("测试闭包方法")
	cl := closure()
	fmt.Println(cl(1))
	fmt.Println(cl(1))
	fmt.Println(cl(1))
	fmt.Println("测试类型switch语句")
	var sl = []int{1, 2} //切片
	for i, v := range sl {
		fmt.Printf("No.%d is %d\n", i+1, v)
	}
	ia := []interface{}{byte(6), 'a', uint(10), int32(-4)} //切片
	switch v := ia[rand.Intn(4)]; v.(type) {
	case interface{}:
		fmt.Printf("%vCase A.", v)
	case byte:
		fmt.Printf("Case B.")
	default:
		fmt.Println("Unknown!")
	}

	fmt.Println("测试类型switch语句")
	map1 := map[int]string{1: "Golang", 2: "Java", 3: "Python", 4: "C"}
	sorted := [4]string{map1[1], map1[2], map1[3], map1[4]}
	for i, v := range sorted {
		//fmt.Printf("%d：%s\n",i,v)
		fmt.Printf("%d: %s\n", i, v)
	}

	fmt.Println("测试类型defer语句")
	deferIt2()

}
func deferIt2() {
	for i := 1; i < 5; i++ {
		defer fmt.Print(i)
	}
}

//该方法返回一个闭包方法func(int) int ，持有了一个i变量，每次调用都会进行i++
func closure() func(int) int {
	i := 0
	return func(int) int {
		i++
		return i
	}
}
